package myJs

import myJs.Implicits._
import myJs.Utils._
import myJs.myPkg.LayerOptions
import myJs.myPkg.jquery._
import org.scalajs.dom._
import org.scalajs.dom.ext.Ajax

import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scala.scalajs.js.Dynamic.{global=>g}
import myJs.tool.Tool
import myJs.tool.Tool._
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("NewPasswordActive")
object NewPasswordActive {
  val count = 10

  @JSExport("init")
  def init = {
    sendEmail
  }

  def refreshRemainTime(count: Int) = {
    Utils.mySetInterval(count, curCount => {
      $("#refreshButton").text(s"${messages("resendTheEmail")}（" + curCount + "）").attr("disabled", true)
    }, () =>
      $("#refreshButton").text(s"${messages("resendTheEmail")}").attr("disabled", false)
    )
  }

  @JSExport("sendEmail")
  def sendEmail = {
    refreshRemainTime(count)
    val url = g.jsRoutes.controllers.AppController.newPasswordEmailValid().url.toString
    val formData = $(s"#form").serialize()
    Ajax.post(url = s"${url}", data = formData, headers = Map("Content-Type" -> "application/x-www-form-urlencoded")).map { xhr =>
      val rs = xhr.responseText.toJDJAn
      val valid = rs("valid").toB
      if (!valid) {
        layer.msg(rs.myGet("message"), LayerOptions.icon(5).time(3000))
      }
    }
  }


}
